<?php
class Serializer{
	private static $xml;


	function __construct(){
		$this->log = new Logger("Serializer", _LOGPATH_);
		$this->log->setLogLevel(Logger::VERBOSE);
		$this->xml = new XmlWriter();
		$this->xml->openMemory();
		$this->xml->startDocument('1.0');
		$this->xml->setIndent(true);
	}

	public function encode($obj) {
		$this->xml->startElement(get_class($obj));
		$this->encodeHelper($obj, get_class($obj));
		$this->xml->endElement();
		return $this->xml->outputMemory(true);
	}

	public function decode($xmlString) {
		return simplexml_load_string($xmlString);
	}

	private function encodeHelper($data, $parentNodeName) {
		if (is_array($data) || is_object($data)) {
			foreach ($data as $key=>$value) {
				if (is_numeric($key)) {
					$key = $parentNodeName;
				}
				$this->xml->startElement($key);
				$this->encodeHelper($value,$key);
				$this->xml->endElement();
			}
		}else{
			$this->xml->writeRaw(htmlspecialchars($data, ENT_QUOTES));
		}
	}
}